/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef LOG_TAG
#define LOG_TAG "AudioSuiteNrNode"
#endif

#include "audio_suite_nr_node.h"

namespace OHOS {
namespace AudioStandard {
namespace AudioSuite {
namespace {
static constexpr AudioSamplingRate NR_ALGO_SAMPLE_RATE = SAMPLE_RATE_16000;
static constexpr AudioSampleFormat NR_ALGO_SAMPLE_FORMAT = SAMPLE_S16LE;
static constexpr AudioChannel NR_ALGO_CHANNEL_COUNT = MONO;
static constexpr AudioChannelLayout NR_ALGO_CHANNEL_LAYOUT = CH_LAYOUT_MONO;
static constexpr uint32_t NR_ALGO_FRAME_LENGTH = 160;      // 10ms data
static constexpr uint32_t NR_ALGO_FRAME_SIZE = NR_ALGO_FRAME_LENGTH * sizeof(int16_t);
}

AudioSuiteNrNode::AudioSuiteNrNode()
    : AudioSuiteProcessNode(AudioNodeType::NODE_TYPE_NOISE_REDUCTION,
          AudioFormat{{NR_ALGO_CHANNEL_LAYOUT, NR_ALGO_CHANNEL_COUNT}, NR_ALGO_SAMPLE_FORMAT, NR_ALGO_SAMPLE_RATE}),
      pcmBufferOutput_(NR_ALGO_SAMPLE_RATE, NR_ALGO_CHANNEL_COUNT, NR_ALGO_CHANNEL_LAYOUT),
      pcmBufferTmp_(NR_ALGO_SAMPLE_RATE, NR_ALGO_CHANNEL_COUNT, NR_ALGO_CHANNEL_LAYOUT)
{}

AudioSuiteNrNode::~AudioSuiteNrNode()
{
    DeInit();
}

int32_t AudioSuiteNrNode::Init()
{
    AUDIO_INFO_LOG("AudioSuiteNrNode::Init begin");

    algoInterface_ = AudioSuiteAlgoInterface::CreateAlgoInterface(AlgoType::AUDIO_NODE_TYPE_NOISE_REDUCTION);
    CHECK_AND_RETURN_RET_LOG(algoInterface_ != nullptr, ERROR, "Failed to create nr algoInterface");

    int32_t ret = algoInterface_->Init();
    CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Failed to Init nr algorithm");

    bufSize_ = pcmBufferOutput_.GetFrameLen() * sizeof(int16_t);
    CHECK_AND_RETURN_RET_LOG(bufSize_ % NR_ALGO_FRAME_SIZE == 0, ERROR, "Invalid PcmBuffer length");
    inputBuffer_ = std::make_unique<uint8_t[]>(bufSize_);
    outputBuffer_ = std::make_unique<uint8_t[]>(bufSize_);

    AUDIO_INFO_LOG("AudioSuiteNrNode::Init end");
    return SUCCESS;
}

int32_t AudioSuiteNrNode::DeInit()
{
    AUDIO_INFO_LOG("AudioSuiteNrNode::DeInit begin");

    if (algoInterface_ != nullptr) {
        algoInterface_->Deinit();
        algoInterface_.reset();
    }

    inputBuffer_.reset();
    outputBuffer_.reset();

    AUDIO_INFO_LOG("AudioSuiteNrNode::DeInit end");
    return SUCCESS;
}

AudioSuitePcmBuffer *AudioSuiteNrNode::SignalProcess(const std::vector<AudioSuitePcmBuffer *> &inputs)
{
    CHECK_AND_RETURN_RET_LOG(!inputs.empty(), &pcmBufferOutput_, "SignalProcess inputs list is empty");

    CHECK_AND_RETURN_RET_LOG(inputs[0] != nullptr, &pcmBufferOutput_, "SignalProcess input data is nullptr");

    CHECK_AND_RETURN_RET_LOG(
        algoInterface_ != nullptr, &pcmBufferOutput_, "SignalProcess algoInterface_ is null, need Init first");

    CHECK_AND_RETURN_RET_LOG(inputBuffer_ != nullptr && outputBuffer_ != nullptr,
        &pcmBufferOutput_, "SignalProcess error, need Init first");

    // clear buffer
    pcmBufferOutput_.Reset();
    memset_s(inputBuffer_.get(), bufSize_, 0, bufSize_);
    memset_s(outputBuffer_.get(), bufSize_, 0, bufSize_);

    // channel and sampleRate convert
    int32_t ret = ConvertProcess(inputs[0], &pcmBufferOutput_, &pcmBufferTmp_);
    CHECK_AND_RETURN_RET(ret == SUCCESS, &pcmBufferOutput_);

    // bitmap convert from float to SAMPLE_S16LE
    ConvertFromFloat(NR_ALGO_SAMPLE_FORMAT,
        pcmBufferOutput_.GetFrameLen(),
        pcmBufferOutput_.GetPcmDataBuffer(),
        static_cast<void *>(inputBuffer_.get()));

    std::vector<uint8_t *> nrAlgoInputs(1);
    std::vector<uint8_t *> nrAlgoOutputs(1);
    uint8_t *frameInputPtr = inputBuffer_.get();
    uint8_t *frameOutputPtr = outputBuffer_.get();
    // apply algo for every frame
    for (uint32_t i = 0; i + NR_ALGO_FRAME_SIZE <= bufSize_; i += NR_ALGO_FRAME_SIZE) {
        nrAlgoInputs[0] = frameInputPtr;
        nrAlgoOutputs[0] = frameOutputPtr;

        ret = algoInterface_->Apply(nrAlgoInputs, nrAlgoOutputs);
        CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, &pcmBufferOutput_, "NR node SignalProcess run Apply fail");

        frameInputPtr += NR_ALGO_FRAME_SIZE;
        frameOutputPtr += NR_ALGO_FRAME_SIZE;
    }

    // bitmap convert from SAMPLE_S16LE to float
    ConvertToFloat(NR_ALGO_SAMPLE_FORMAT,
        pcmBufferOutput_.GetFrameLen(),
        static_cast<void *>(outputBuffer_.get()),
        pcmBufferOutput_.GetPcmDataBuffer());

    return &pcmBufferOutput_;
}

}  // namespace AudioSuite
}  // namespace AudioStandard
}  // namespace OHOS